
function hijax_student_edit_form() {
    /* validate signup form on keyup and submit */ 
    var edit_form = $("#user");
    var validator = edit_form.validate({
    		rules: { 
            firstname: "required", 
            lastname: "required", 
            username: { 
                required: true, 
                minlength: 2, 
                remote: edit_form.attr("action") + "validate_username/",
            }, 
            email: { 
                required: true, 
                email: true,
            },
            password: {
                minlength: 5,
            }, 
            passwordconfirmation: {
                minlength: 5, 
                equalTo: $("input[name='password']")[0],
            },
            room: {
            	required: false,
            },
        }, 
        messages: {
           	username: { 
            	required: "Enter a username",
             	remote: jQuery.format("{0} is already in use"),
        		},
        },
        errorPlacement: function(error, element) {
        		error.appendTo( element.parent().next() ); 
        }, 
        errorContainer: "authform_errors",
        success: function(label) { 
            /* set   as text for IE */
            label.html(" ").addClass("checked"); 
        },
		  submitHandler: function(form) {
		  		$(form).ajaxSubmit({
    				success: function(data) {
    					var studentid = $("#user_object_id").val();
    					$(form).replaceWith(data);
    					if (data == ""){ /* succes */
    						var url = $(form).attr('action') + "?ajax=true&section=general_info";
    						$.get(url, function(data) {
    							$("#student_general_info_wrapper").html(data);
    							$("#student_edit_link").show();
    						});
    						update_student_row(studentid);
    					}
    					else {
    						hijax_student_edit_form();
    					}
    				},
    			});
		  },
    });
    
    hijax_form(edit_form);
}

function update_student_row(studentid) {
	var student_row = document.getElementById("student_row_" + studentid);
	if (student_row) {
		var url = "/students/?ajax=true&row=" + studentid;
		$.get(url, function(data) {
			$(student_row).html(data);
			student_row.update_cache();
		});
	}
}

$(document).ready(function() { 
	hijax_student_edit_form();
});
